import json
import re
from collections import defaultdict
from datetime import datetime, timedelta
from time import sleep
from typing import List, Tuple, Dict

import MySQLdb
import requests

import config

white_buildings = ['逸夫楼', '教学楼', '信息楼', '冶金楼', '管理楼', '机械楼', '外语楼', '理化楼', '土木楼',
                   "管庄教学楼", "昌平南楼"]
# not in 一定不是无课教室
white_list = {
    "理化楼": lambda x: int(x) in [308],
    "管理楼": lambda x: int(x[0]) <= 5,
    "冶金楼": lambda x: x in ['110', '201', '202', '203', '204', '205', '210'],
    "教学楼": lambda x: int(x) in [101, 102, 103, 105, 107, 201, 202, 203, 301, 303, 305, 401, 403, 405, 402, 407, 409,
                                   509, 502, 507, 505],
    "文法楼": lambda x: int(x) not in [108, 304, 306],
    "土木楼": lambda x: int(x) not in [203],
    # "信息楼": lambda x: int(x) not in [824],
    "逸夫楼": lambda x: x[0] != "8",
}

# 缓存未来的天数
cache_days = 3


def handler(date: datetime):
    db = MySQLdb.connect(
        host="127.0.0.1",  # 主机名
        user="schedule",  # 用户名
        passwd="f9T,Hh6i%b*D",  # 密码
        db="schedule",
        charset='utf8',
        use_unicode=True)

    cur = db.cursor()
    date_text = date.strftime("%Y-%m-%d")
    #ServerUrl = 'https://ibeike.ustb.e/teach_week/'
    ServerUrl = 'http://127.0.0.1:60041/'
    r = requests.get(f'{ServerUrl}?date={date_text}', verify=False).json()
    week = r['real']['week'] - 1
    day = r['real']['day'] - 1

    cur.execute('''select distinct periods from courses''')  # 取唯一的值
    data = cur.fetchall()  # 返回元组
    data = [json.loads(i[0]) for i in data]
    data1 = [i[j] for i in data for j in range(len(i)) if ("classroom" in i[j])]

    result: Dict[int, List[Tuple]] = {_: [] for _ in range(6)}
    for row in data1:
        if week in row['weeks'] and day == row['day']:
            # result[row['order']].append({"building":row['building'],"classroom":row['classroom']})
            result[row['order']].append((row['building'], row['classroom']))

    # 所有教室信息
    memory = set()
    classrooms_by_building = defaultdict(list)
    classrooms = []
    for i in data:
        for x in i:
            if ("classroom" in x):
                buildclassroom = x["building"] + x["classroom"]
                if (buildclassroom not in memory):
                    memory.add(buildclassroom)
                    classrooms.append((x["building"], x["classroom"]))
                    classrooms_by_building[x["building"]].append(x["classroom"])
                else:
                    pass
            else:
                pass

    # print(json.dumps({k: ','.join(sorted(v)) for k, v in classrooms_by_building.items()}, indent=2, ensure_ascii=False))

    sql_items = []
    for i in result:  # i是order
        result[i] = list(set(classrooms) - set(result[i]))
        for item in result[i]:
            # white_buildings中才统计 然后需要根据white_list过滤一下
            if item[0] in white_buildings and (item[0] not in white_list or white_list[item[0]](item[1])):
                sql_items.append({
                    'building': item[0],
                    'num': i + 1,
                    'day': date_text,
                    'classroom': item[1]
                })

    cur.close()
    db.close()
    save_data(sql_items)

    # for j in sql_items:
    #     if(j[3][0]=='逸夫楼' and j[2]==1):
    #         print (j)


def save_data(data):
    db = MySQLdb.connect(
        host=config.DB_HOST,  # 主机名
        port=config.DB_PORT,
        user=config.DB_USERNAME,  # 用户名
        passwd=config.DB_PASSWORD,  # 密码
        db=config.DB_DATABASE,
        charset='utf8',
        use_unicode=True)
    db.autocommit(False)
    cur = db.cursor()
    # print(data)
    try:
        sql = "delete from rest_rooms where day = '%s'" % (data[0]['day'])
        cur.execute(sql)
        sql = "insert into rest_rooms(day, num, building, classroom) values %s" % (
            ','.join([f"('{i['day']}',{i['num']},'{i['building']}','{i['classroom']}')" for i in data]))  # 查询新插入的数据
        cur.execute(sql)
    except Exception as e:
        print('fail', e)
        db.rollback()
    else:
        db.commit()
    db.close()


def fetch():
    print('fetch')
    today = datetime.today()
    print([today + timedelta(days=i) for i in range(cache_days)])
    for d in [today + timedelta(days=i) for i in range(cache_days)]:
        handler(d)
    print('fetch finish')


store = {}


def main():
    while True:
        today = datetime.now().strftime("%Y-%m-%d")
        if today not in store:
            fetch()
            store[today] = None
        sleep(60 * 60 * 6)


if __name__ == '__main__':
    main()
